package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.wing.cabinet.dao.CellInventoryInoutDao;
import com.wing.cabinet.model.entity.CellInventoryInout;
import com.wing.cabinet.model.entity.StorageInventoryInout;
import com.wing.cabinet.model.request.CellInventoryInoutForm;
import com.wing.cabinet.model.response.*;
import com.wing.cabinet.utils.DjInterfaceAbutment;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.DepartmentVO;
import com.wing.user.model.response.UserVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 售刀柜上货(上货主表无展示)/领取-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CellInventoryInoutServiceImpl extends ServiceImpl<CellInventoryInoutDao, CellInventoryInout> implements CellInventoryInoutService {
    @Autowired
    private StorageInventoryInoutService storageInventoryInoutService;
    @Autowired
    private UserClient userClient;
    /**
     * 模拟缓存服务
     */
    private static final Map<String,String> SYSTEM_CACHE = new HashMap<>();
    /**
     * ecology系统发放的授权许可证(appid)
     */
    private static final String APPID = "OAAPPID2023";
    @Override
    public int add(CellInventoryInoutForm cellInventoryInoutForm) {
        //校验
        CellInventoryInout cellInventoryInout =new CellInventoryInout();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CellInventoryInout.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cellInventoryInoutForm, cellInventoryInout, copyOptions);
        return baseMapper.insert(cellInventoryInout);
    }

    @Override
    public List<CellInventoryInoutVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public List<CellInventoryInoutVO> list(Map<String, Object> params) {
        return baseMapper.list(null,params);
    }

    @Override
    public Page<CellInventoryInoutVO> pageList4app(Page page, Map<String, Object> params) {
        List<CellInventoryInoutVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CellInventoryInoutVO> pageList(Page page, Map<String, Object> params) {
        List<CellInventoryInoutVO> list = baseMapper.list(page, params);
        for(CellInventoryInoutVO item : list){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            if(null != jsonResult && null != jsonResult.getData()) {
                item.setCostCenter(jsonResult.getData().getCostCenter());
            }
            JsonResult<DepartmentVO> jsonResult2 = userClient.getDepartmentVOById(item.getDeviceDepartmentId());
            if(null != jsonResult2 && null != jsonResult2.getData()) {
                item.setDeviceDepartmentName(jsonResult2.getData().getName());
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CellInventoryInoutVO> pageList4OldNew(Page page, Map<String, Object> params) {
        List<CellInventoryInoutVO> list = baseMapper.list4OldNew(page, params);
        for(CellInventoryInoutVO item : list){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            if(null != jsonResult &&  null != jsonResult.getData()) {
                item.setCostCenter(jsonResult.getData().getCostCenter());
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public CellInventoryInoutVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public CellInventoryInoutVO get4appByInOutIdAndSkuCode(Long id, String skuCode) {
        return baseMapper.get4appByInOutIdAndSkuCode(id,skuCode);
    }


    @Override
    public Map<String, Integer> getCount() {
        //领用订单
        QueryWrapper<CellInventoryInout> inoutQueryWrapper = new QueryWrapper<>();
        inoutQueryWrapper.eq("creator", JwtUtils.getLoginUserId());
        inoutQueryWrapper.eq("type",CellInventoryInout.Type.out.getValue());
        int pickOrder = this.list().size();

        //维修订单
        QueryWrapper<StorageInventoryInout> sinoutQueryWrapper = new QueryWrapper<>();
        sinoutQueryWrapper.eq("creator", JwtUtils.getLoginUserId());
        sinoutQueryWrapper.eq("business_type", 2);
        int repairOrder = storageInventoryInoutService.count(sinoutQueryWrapper);

        //回收订单
        QueryWrapper<StorageInventoryInout> stinoutQueryWrapper = new QueryWrapper<>();
        stinoutQueryWrapper.eq("creator", JwtUtils.getLoginUserId());
        stinoutQueryWrapper.eq("business_type", 3);
        int recycleOrder = storageInventoryInoutService.count(stinoutQueryWrapper);

        Map<String, Integer> map = new HashMap<>();
        map.put("pickOrder",pickOrder);
        map.put("repairOrder",repairOrder);
        map.put("recycleOrder",recycleOrder);
        return map;
    }

    @Override
    public List<NeckNewExportVO> ecxportList(Map<String, Object> params) {
        List<NeckNewExportVO> list = baseMapper.getNeckNewExportList(params);
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US);
        /*for (int i =0;i<list.size();i++) {
            Integer num=list.get(i).getQuantity();
            if (num<0){
                num = num * -1;
                list.get(i).setQuantity(num);
            }
        }*/

        return list;
    }

    @Override
    public List<OldNeckNewExportVO> getOldNeckNewExportVOList(Map<String, Object> params) {
        return baseMapper.getOldNeckNewExportVOList(params);
    }

    @Override
    public void syncBill(Integer[] ids) {
        if(ids.length == 0){
            throw new BusinessException("合并账单参数异常");
        }
        Map paramsMap = new HashMap();
        paramsMap.put("types",new Integer[]{CellInventoryInout.Type.out.getValue(),CellInventoryInout.Type.outByCabSpace.getValue()});
        paramsMap.put("ids",ids);
        List<CellInventoryInoutVO> inventoryInoutVOList = baseMapper.list(paramsMap);
        for(CellInventoryInoutVO item : inventoryInoutVOList){

        }

    }

    @Override
    public void syncDjCellInventoryInoutData() {
        DjInterfaceAbutment djInterfaceAbutment = new DjInterfaceAbutment();
        //查询所有部门
        JsonResult<List<DepartmentVO>> jsonResult = userClient.getDepartmentList();

        String detailParamsStr = null;
        Map queryParam=new HashMap();
        queryParam.put("exportType",1);
        queryParam.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        queryParam.put("timing", "lastMonth");
        //子表数据
        ArrayList<DetailParamsVO> detailParamsList = new ArrayList<>();
        DetailParamsVO detailParamsVO = new DetailParamsVO();
        detailParamsVO.setTableDBName("formtable_main_279_dt1");
        ArrayList<WorkflowRequestTableRecords> recordsList = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (DepartmentVO item : jsonResult.getData()){
            queryParam.put("departmentId",item.getId());
            List<CellInventoryInoutVO> InoutVOList = baseMapper.list(null, queryParam);
            Gson gson = new Gson();
            if(CollectionUtils.isNotEmpty(InoutVOList)){
                //主表数据
                JsonResult<UserVO> userVOJsonResult = userClient.getUserInfoByUserId(InoutVOList.get(0).getCreator());
                ArrayList<DjCellInventoryInoutVO> arrayList = new ArrayList<>();
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("tdr")
                        .setFieldValue(userVOJsonResult.getData().getThirdPartyUserId() == null ? null : userVOJsonResult.getData().getThirdPartyUserId().toString()));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("tdrbm")
                        .setFieldValue(userVOJsonResult.getData().getThirdPartyDepartmentId() == null ? null :userVOJsonResult.getData().getThirdPartyDepartmentId().toString()));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("ddlx").setFieldValue("MNB2"));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("sqrq").setFieldValue(formatter.format(date)));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("gs").setFieldValue("3000"));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("cgzz").setFieldValue("3000"));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("gys").setFieldValue("M160010"));
                arrayList.add(new DjCellInventoryInoutVO().setFieldName("cgz").setFieldValue("517"));
                String mainDataStr = gson.toJson(arrayList);
                System.out.println("mainData" + mainDataStr);
                for (CellInventoryInoutVO inoutVoItem : InoutVOList){
                    WorkflowRequestTableRecords records = new WorkflowRequestTableRecords();
                    records.setRecordOrder(0);
                    ArrayList<DjCellInventoryInoutVO> arrayDetailList = new ArrayList<>();
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("lyddbh")
                            .setFieldValue(inoutVoItem.getCode()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("wlbh")
                            .setFieldValue(inoutVoItem.getSkuCode()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("wlmc").setFieldValue(inoutVoItem.getSkuName()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("pp").setFieldValue(inoutVoItem.getProductBrandName()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("ggm").setFieldValue(inoutVoItem.getSkuSpecOld()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("fls").setFieldValue(inoutVoItem.getQuantityPack().toString()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("lqr").setFieldValue(inoutVoItem.getCreatorName()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("sbbm").setFieldValue(inoutVoItem.getDeviceCode()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("cbzx").setFieldValue(item.getCostCenter()));
                    arrayDetailList.add(new DjCellInventoryInoutVO().setFieldName("lqsj").setFieldValue(dateTimeFormatter.format(item.getCreateTime())));
                    records.setWorkflowRequestTableFields(arrayDetailList);
                    recordsList.add(records);
                }
                detailParamsVO.setWorkflowRequestTableRecords(recordsList);
                detailParamsList.add(detailParamsVO);
                detailParamsStr = gson.toJson(detailParamsList);
                System.out.println("子表数据" + detailParamsStr);
                //输出
                String testRestful = djInterfaceAbutment.testRestful("http://116.6.107.206:8085", "/api/workflow/paService/doCreateRequest"
                        , mainDataStr, detailParamsStr, userVOJsonResult.getData().getThirdPartyUserId().toString());
                //System.out.println("testRestful:东江接口对接，部门名称:" + item.getName() + "--部门ID---" + item.getId() + "---返回值：" + testRestful);
                System.out.println("testRestful:东江接口对接:"  + "---返回值：" + testRestful);
            }
        }
    }

    @Override
    public List<CellInventoryInoutApiVO> syncCellInventoryInoutList(Map<String, Object> params) {
        return baseMapper.syncCellInventoryInoutList(params);
    }

    @Override
    public Page<CellInventoryInoutVO> pageListNew(Page page, Map<String, Object> params) {
        List<CellInventoryInoutVO> list = baseMapper.pageListNew(page, params);
        for(CellInventoryInoutVO item : list){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            if(null != jsonResult && null != jsonResult.getData()) {
                item.setCostCenter(jsonResult.getData().getCostCenter());
            }
            JsonResult<DepartmentVO> jsonResult2 = userClient.getDepartmentVOById(item.getDeviceDepartmentId());
            if(null != jsonResult2 && null != jsonResult2.getData()) {
                item.setDeviceDepartmentName(jsonResult2.getData().getName());
            }
        }
        page.setRecords(list);
        return page;
    }


}
